package com.zhkj.txg.module.home.vm

import android.app.Application
import androidx.lifecycle.MutableLiveData
import com.zhkj.lib.base.BaseViewModel
import com.zhkj.lib.http.HttpResponse
import com.zhkj.lib.http.ViewModelSubscribeListener
import com.zhkj.txg.module.home.entity.TopDataResponse
import com.zhkj.txg.module.home.entity.TopProductResponse
import com.zhkj.txg.module.home.model.HomeManager

class TopViewModel(application: Application) : BaseViewModel(application) {
    private val homeManager = HomeManager()
    val topLiveData = MutableLiveData<HttpResponse<TopDataResponse>>()
    val topProductLiveData = MutableLiveData<HttpResponse<TopProductResponse>>()

    private var page = 1
    private val numb = 20

    fun topData(token: String) {
        val listener = object : ViewModelSubscribeListener<TopDataResponse>(topLiveData) {
            override fun onSuccess(resp: TopDataResponse) {
                super.onSuccess(resp)
                page = 1
                topProduct(token)
            }
        }
        val topData = homeManager.topData(token, listener)
        dispose.add(topData)
    }

    fun topProduct(token: String, restart: Boolean = false) {
        if (restart) page = 1
        val listener = object : ViewModelSubscribeListener<TopProductResponse>(topProductLiveData) {
            override fun onSuccess(resp: TopProductResponse) {
                resp.hasMore = resp.data.size >= 20
                resp.loadMore = page > 1
                super.onSuccess(resp)
                page += 1
            }
        }
        val topProduct = homeManager.topProduct(token, page, numb, listener)
        dispose.add(topProduct)
    }
}